﻿@inject DialogService DialogService
@inject ProductService ProductService
@inject ProductUnitService ProductUnitService

<RadzenStack>
    <RadzenTemplateForm EditContext="editContext" TItem="Unit" Data="@model" Submit=@OnSubmit>
        <RadzenStack Gap="1rem">
            <RadzenStack class="rz-p-0" Orientation="Orientation.Vertical" AlignItems="AlignItems.Start" JustifyContent="JustifyContent.Normal">
                <RadzenRow Gap="1rem">
                    <RadzenColumn Size="12" SizeMD="12">
                        <RadzenStack>
                            <RadzenFormField Text="名称" Style="width: 100%;">
                                <ChildContent>
                                    <RadzenTextBox Name="Name" @bind-Value="@PUnit.Name" />
                                    <RadzenRequiredValidator Component="Name" Text="名称不能为空。" Popup=true Style="position: absolute" />
                                </ChildContent>
                                <Helper>
                                    <RadzenText TextStyle="TextStyle.Caption" Style="color:red">* 必填</RadzenText>
                                </Helper>
                            </RadzenFormField>
                        </RadzenStack>
                    </RadzenColumn>
                </RadzenRow>
            </RadzenStack>
            <RadzenStack Gap="1rem" Orientation="Orientation.Horizontal" JustifyContent="JustifyContent.End" Style="height: 20%;">
                <RadzenButton ButtonStyle="ButtonStyle.Secondary" Text="取消" Click="OnCancel" />
                <RadzenButton ButtonStyle="ButtonStyle.Primary" Text="保存" ButtonType="ButtonType.Submit" />
            </RadzenStack>
        </RadzenStack>
    </RadzenTemplateForm>
</RadzenStack>

@code {
    [Parameter] public Unit PUnit { get; set; }

    private EditContext? editContext;
    private Unit? model = default!;

    void OnSubmit(Unit model)
    {
        try
        {
            var result = ProductUnitService.Save(model);
            DialogService.Close(result);
        }
        catch (Exception e)
        {
            DialogService.Alert(e.Message, "错误", new AlertOptions() { OkButtonText = "确定" });
        }
    }

    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
        
        model = PUnit!;
        editContext = new EditContext(model);
    }

    private void OnCancel()
    {
        ProductService.ResetOriginalData();
        DialogService.Close(null);
    }

}

